package org.boot.fast.util;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@SuppressWarnings("all")
@Slf4j
public class GsonUtil {

    private static Gson gson = new Gson();

    public static Gson getGson() {
        return gson;
    }
    public static Integer[] toIntArray(String jsonArray) {
        try {
            return gson.fromJson(jsonArray, Integer[].class);
        } catch (Exception e) {
            throw new RuntimeException("JSON转换失败: " + e.getMessage(), e);
        }
    }

    public static Object toList(Object value) {
        if (value == null) {
            return Collections.emptyList();
        }
        String str = value.toString().trim();
        if (str.isEmpty()) {
            return Collections.emptyList();
        }

        // 1. 尝试 JSON 数组
        if (str.startsWith("[") && str.endsWith("]")) {
            try {
                return gson.fromJson(str, List.class);
            } catch (JsonSyntaxException e) {
                log.warn("不是合法 JSON 数组，降级为逗号拆分: {}", str);
            }
        }
        try{
            return Arrays.stream(str.split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.warn("不是合法的数据格式: {}", str);
            return value;
        }
    }
}
